﻿//==============================================================================  
//Copyright (C) 2012-2015 9UN.ORG. All rights reserved. 
//GUID：9d126cdd-d129-407f-a1d3-5d72974d36f6
//CLR Version: 4.0.30319.18033
//Code Author：Kevin Wang
//Contact：Email(Admin@9un.org),QQ(265382 or 74344)
//Filename：PDFFileProxy
//Namespace：RuanRang.Core
//Functions：PDFFileProxy  
//Created by Kevin Wang at 2013/2/2 23:25:26 http://blog.9un.org
//============================================================================== 

using System;
using System.Drawing;
using System.IO;
using System.Reflection;

namespace RuanRang.Core.Render
{
    public class PDFRender : DocumentRender
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PDFRender"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        public PDFRender(RenderPluginContainer container)
        {
            TargetType = container.Resolve(RenderPluginType.PDF, "O2S.Components.PDFRender4NET.PDFFile");
        }

        /// <summary>
        /// Opens the specified file path.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>System.Object.</returns>
        public override void Open(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new IOException("PDF文件不存在，路径：" + filePath);
            }
            const BindingFlags accessStaticMethod = BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod;
            //获取PDF实例
            TargetFile = TargetType.InvokeMember("Open", accessStaticMethod, Type.DefaultBinder, null, new object[] { filePath });
            const BindingFlags accessPublicProperty = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance;
            //获取页面数量
            var property = TargetType.GetProperty("PageCount", accessPublicProperty);
            PageCount = (int)property.GetValue(TargetFile, null);
        }

        /// <summary>
        /// Gets the image.
        /// </summary>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="resolution">The resolution.</param>
        /// <returns>Bitmap.</returns>
        public override Image GetImage(int pageIndex, float resolution = 100)
        {
            const BindingFlags accessPublicMethod = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance;
            var image =(Bitmap)TargetType.InvokeMember("GetPageImage", accessPublicMethod, Type.DefaultBinder, TargetFile, new object[] { pageIndex, resolution });
            var result = image.Clone() as Image;
            image.Dispose();
            return result;
        }
    }
}
